<template>
  <el-dialog v-model="state.visible" title="文件内容" :close-on-click-modal="false">
    <div style="height: 400px; overflow: scroll">
      <article v-highlight v-html="state.content"></article>
      <el-button class="clipboard-btn" type="primary" text bg @click="copyHandle($event)">复制</el-button>
    </div>
    <template #footer>
      <el-button @click="state.visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {useTemplateFileContentByFileId} from '@/api/templateFile'
import {marked} from "marked";
import Clipboard from "clipboard";
import {ElMessage} from "element-plus";

const state = reactive({
  // 对话框状态
  visible: false,
  // 文件 ID
  id: '',
  // 文件类型
  fileType: '',
  // 文件内容
  content: '',
  // 文件源
  source: ''
})

/**
 * 初始化
 * @param id 文件 id
 * @param fileType 文件类型
 */
const init = (id: string, fileType: string) => {
  state.visible = true
  // 数据 ID
  state.id = id
  // 文件类型
  state.fileType = fileType
  // 文件内容清空
  state.source = ''
  state.content = ''
  // 获取文件内容
  getFileContent(id)
}

const getFileContent = (id: number | string) => {
  useTemplateFileContentByFileId(id).then((res) => {
    state.source = res.data
    state.content = marked.parse(
        '```' + state.fileType + '\n' +
        state.source +
        '\n```'
    )
  })
}


// 赋值内容
const copyHandle = (e: PointerEvent) => {
  // 剪贴板
  const clipboard = new Clipboard(e.currentTarget as any, {
    action: () => 'copy',
    text: () => state.content
  })
  // 成功
  clipboard.on('success', () => {
    ElMessage.success('复制成功')
    clipboard.destroy()
  })
  // 异常
  clipboard.on('error', () => {
    ElMessage.success('复制失败')
    clipboard.destroy()
  })
}

defineExpose({
  init
})
</script>

<style lang="scss">

.clipboard-btn {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.1)
}
</style>

